<template>
  <div class="outer-input" :style="{width:`${width}%`}">
    <div class="input-title">
        <span class="need" v-if="struc?.must">*</span>
        <span class="label-name">{{ struc?.viewName }}</span>
    </div>
    <div class="input-contextPackage">
      <el-select 
				v-model="oneValue" 
				:placeholder="struc?.hint" 
				@blur="out($event)"
				@change="out($event)"
				class="select-3"
        clearable
				>
				<el-option
					v-for="item in defaultOptions"
					:key="item.id"
					:label="item.name"
					:value="item.id">
				</el-option>
			</el-select>
      <el-select 
				v-model="twoValue" 
				placeholder="请选择" 
				v-show="oneValue"
				class="select-3"
				>
				<el-option
					v-for="item in defaultTwoOptions"
					:key="item.id"
					:label="item.name"
					:value="item.id">
				</el-option>
			</el-select>
      <el-select 
				v-model="threeValue" 
				placeholder="请选择" 
				v-show="twoValue && !isFriend"
				class="select-3"
				>
				<el-option
					v-for="item in defaultThreeOptions"
					:key="item.id"
					:label="item.name"
					:value="item.id">
				</el-option>
			</el-select>
      <zsearchname v-if="twoValue && isFriend" @setName="setName" :personName="personName" ></zsearchname>
      <div class="operation-icon" @click="handleOpen">
        <el-icon><tools /></el-icon>
      </div>
      <span class="errorhint" v-if="showError">{{
        struc?.errorHit
      }}</span>
    </div>
  </div>
  <!-- {{valueInput.value}} -->

  <zdialog title="患者来源配置" @handleClose="closeDialog" v-model="openConfigSource" :btnData="dialogBtnData">
			<template #body>
        <div class="config-source">
          <div class="source source-one">
            <div class="title">患者来源一</div>
            <div class="display-area">
              <ul>
                <li class="item" v-for="item in defaultOptions" @click="handleItemOne(item.name)">{{item.name}}</li>
              </ul>
            </div>
          </div>
          <div class="source source-two">
            <div class="title">患者来源二</div>
            <div class="display-area">
              <ul>
                <li class="item" v-for="item in defaultTwoOptions" @click="handleItemTwo(item)">{{item.name}}</li>
              </ul>
            </div>
          </div>
          <div class="source source-three">
            <div class="title">患者来源三</div>
            <div class="display-area">
              <div class="area-title">
                <span>名称</span>
                <span>操作</span>
              </div>
              <ul>
                <li class="item area-active" v-for="(item, index) in defaultThreeOptions" @click="handleItemThree(item.name)">
                <span v-if="!isFriend">
                  <span v-if="!item.isEdit">{{item.name}}</span>
                  <el-input v-if="item.isEdit" class="input-7" v-model="item.name"></el-input>
                </span>
                
                <span class="area-operation">
                  <span v-if="!item.isEdit" @click="handleItemEdit(item, index)"><el-icon><edit /></el-icon></span>
                  <span v-if="!item.isEdit" @click="handleItemDel(item, index)"><el-icon><delete /></el-icon></span>
                  <span v-if="item.isEdit" @click="handleItemSave(item, index)"><el-icon><check /></el-icon></span>
                  <span v-if="item.isEdit" @click="handleItemCancel(item, index)"><el-icon><close /></el-icon></span>
                </span>

                </li>
              </ul>
              <span class="not-eidt-item" v-if="isFriend">该配置不可编辑</span>
              <!-- 新增 -->
              <template v-if="isShow">
                <div class="add-item-opration">
                  <span>
                    <el-input class="input-7" v-model="addSourceName"></el-input>
                  </span>
                  <span class="area-operation">
                    <span @click="handleItemAddSave()"><el-icon><check /></el-icon></span>
                    <span @click="handleItemAddCancel()"><el-icon><close /></el-icon></span>
                  </span>
                </div>
              </template>
              <span class="add-item" v-if="!isFriend && !isShow && defaultTwoOptions.length > 0" @click="handleAddItem">
                <el-icon><plus /></el-icon>新增
              </span>
            </div>
          </div>
        </div>
			</template>
	</zdialog>
</template>

<script lang="ts">
import { Tools, Plus, Check, Close, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { defineComponent, onMounted, PropType, ref, reactive, computed, watch, watchEffect, defineAsyncComponent, nextTick } from "vue";
import useDataCheck, { DataStruc } from "../../hook/datastruc";
import useRequest from '../../hook/request';
import { useRoute } from 'vue-router'

type DefaultOption = {
  id: string,
  name: string,
  isEdit?: boolean,
  subType?: string,
}

type MockOPtions = {
  name: string,
  options: DefaultOption[]
}
export default defineComponent({
  type: 333,
  name: "MultiConfig",
  components: {
    zsearchname: defineAsyncComponent(() => import('../searchinput/searchName.vue')),
    zdialog: defineAsyncComponent(() => import('@components/dialog/dialog.vue')),

    Tools,Plus, Check, Close, Edit, Delete
  },
  props: {
    struc: {
      type: Object as PropType<DataStruc>,
    },
    passWidth: {
			type: Number
		}
  },
  setup: (props, context) => {
    const route = useRoute()
    let id = route.params.id
    let showError = ref(false);
    let valueInput: DataStruc = reactive(props.struc as DataStruc);
    const dataCheck = useDataCheck();
    const defaultOptions = ref<DefaultOption[]>([])
    const defaultOptionsList = ['介绍', '家住附近', '市场部', '广告', '默认来源']
    const isShow =ref (false)
    const setDefaultOptions = (arr: string[]) => {
      arr.forEach(item => {
        defaultOptions.value.push({
          id:item,
          name: item
        })
      })
    }
    setDefaultOptions(defaultOptionsList)
    const oneValue = ref('')
    // 用于配置
    const oneConfigValue = ref('')
    const twoConfigValue = ref('')
    const getMockOptionsTwo = async(val: string) => {
      let result:any = await useRequest('customer/info/getCustomerSecondSourceList', {
        parentValue: val
      }, 'POST')
      defaultTwoOptions.value = result.data || []
    }
    
    // 二级下拉关联数据
    const mockOPtions = <MockOPtions[]>[]
    // 二级数据
    const twoValue = ref<string | number>('')
    const defaultTwoOptions = ref<DefaultOption[]>([])
    // 三级下拉关联数据
    const mockOptionThree = <MockOPtions[]>[]
    const getMockOptionThree = async(id: number) => {
      let result:any = await useRequest('customer/info/getCustomerSourceDistList', {
        parentId: id
      }, 'POST')
      defaultThreeOptions.value = result.data || []
      defaultThreeOptions.value.forEach((item:any) => item.isEdit = false)
    }
    // 侦听一级数据的变化
    watch(() => [oneValue.value, oneConfigValue.value], ([newV, newTV]) => {
      
      isFriend.value = false;
      twoValue.value = ''
      threeValue.value = ''
      defaultThreeOptions.value = []
      let val = newV || newTV
      if(newV || newTV) {
        getMockOptionsTwo(val)
      }
      if(newV) {
        valueInput.value = `${newV}`
      } 
      if(twoValue.value) {
        valueInput.value = `${newV}|${twoValue.value}|${threeValue.value}`
      }
      
      
      console.log('一级数据变化', twoValue.value, newV , newTV)
      
    })

    // 侦听二级数据的变化
    watch(() => [twoValue.value, twoConfigValue.value], ([newV, newTV]) => {
      console.log('二级数据变化', twoValue.value, newV , newTV)
      threeValue.value = ''
      let resObj = defaultTwoOptions.value.find(item => {
        return item.id == newV || item.id == newTV
      })

      if(resObj?.subType && resObj?.subType == '用户' || resObj?.subType == '患者') {
        isFriend.value = true;
        isShow.value = false
      } else {
        isFriend.value = false;
        if(newV || newTV) {
            let id = newV || newTV
            getMockOptionThree(Number(id))
        }
        if(newV) {
          valueInput.value = `${oneValue.value}|${newV}`
        }
      }
      
      
    })
    const isFriend = ref(false)
    const threeValue = ref<string | number>('')
    const defaultThreeOptions = ref<DefaultOption[]>([])
    // 侦听三级数据的变化
    watch(() => threeValue.value, (newV) => {
      valueInput.value = `${oneValue.value}|${twoValue.value}|${newV}`
      // isFriend.value = false;
    })
    const setName = (name: any) => {
      threeValue.value = name.id
    }
    const handleInput = (e: string) => {
      console.log(e)
    }
    const personName = ref<string | number>('')

    // 判断 二级来源值 区分
    const setConfigVal = (id: number | string) => {
      let res = defaultTwoOptions.value && defaultTwoOptions.value.find(item => item.id == id);
      return res?.subType ? res.subType : ''
    }
    watchEffect(() => {
      if(valueInput.value) {
        showError.value = false;
        let list = valueInput.value.toString().split('|');
          oneValue.value = list[0] || ''
          if(list.length > 1 && list[1]) {
            twoValue.value = Number(list[1])
          }
          
          if(twoValue.value) {
            getMockOptionThree(Number(twoValue.value))
            
            if(setConfigVal(twoValue.value) == '患者' || setConfigVal(twoValue.value) == '用户') {
              isFriend.value = true;
            } else {
              threeValue.value = Number(list[2]) || ''
            } 
          }
          
          
          
        
      }
    })

    

    const customerInfo = ref<any>({})
    // 回显特殊的输入框
    const echoSpecialVal = ref('')
    const getPersonDetailInfo = async() => {
      let result:any = await useRequest(`customer/info/getCustomerInfoDetail/${id}`, {}, 'GET')
      customerInfo.value = result.data.customerInfo;
      echoSpecialVal.value = customerInfo.value.scoreShow;
      let data = echoSpecialVal.value.split('|')
      if(setConfigVal(twoValue.value)  == '患者' || setConfigVal(twoValue.value) == '用户' && isFriend.value) {
        data.length === 3 ? personName.value = data[2] : ''
      }

    }
    if(id) {
      getPersonDetailInfo()
    }
    

    // 配置框
    const openConfigSource = ref(false)
    const closeDialog = () => {
      openConfigSource.value = false;
      oneConfigValue.value = ''
      twoConfigValue.value = ''
      defaultTwoOptions.value = []


    }

    // 打开配置框
    const handleOpen = () => {
      openConfigSource.value = true
    }
    const dialogBtnData = [
      {
        name: '关闭',
				func: (data:object) => {
					// console.debug('关闭',JSON.parse(JSON.stringify(data)))
          closeDialog()
				}
      }
    ]
    
    const handleItemOne = (name: string) => {
      oneConfigValue.value = name
    }

    const handleItemTwo = (data: any) => {
      ParentId.value = data.id
      twoConfigValue.value = data.id
    }

    const handleItemThree = (name: string) => {
      console.log('三', name)
    }

    
    const ParentId = ref()
    const addSourceName = ref('')
    const handleAddItem = () => {
      isShow.value = true
    }
    const handleItemAddSave = async() => {
      let result:any = await useRequest('customer/info/addCustomerSourceDist', {
        parentId: ParentId.value,
        sourceValue: addSourceName.value
      }, 'POST')
      getMockOptionThree(ParentId.value)
      addSourceName.value = ''
      isShow.value = false
    }
    const handleItemAddCancel = () => {
      isShow.value = false
    }

    const handleItemEdit = (data: any, index: number) => {
      defaultThreeOptions.value[index].isEdit = true
    }
    // 修改的保存
    const handleItemSave = async(data: any, index: number) => {
      let result:any = await useRequest('customer/info/updateCustomerSourceDist', {
        parentId: data.parentId,
        sourceValue: data.name
      }, 'POST')
      getMockOptionThree(data.parentId)
      defaultThreeOptions.value[index].isEdit = false

    }
    const handleItemCancel = (data: any, index: number) => {
      defaultThreeOptions.value[index].isEdit = false
    }

    const handleItemDel = async(data: any, index: number) => {
      ElMessageBox.confirm('此操作将删除该来源, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async() => {
        
        let result:any = await useRequest(`customer/info/delCustomerSourceDist/${data.id}`, {}, 'POST')
        getMockOptionThree(data.parentId)
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
    }

    let check = () => {
      if(props.struc?.must) {
        if (props.struc.value) {
          showError.value = false;
        } else {
          console.debug("检查出错：", showError);
          props.struc.errorHit = `请输入${props.struc.viewName}`
          showError.value = true;
        }
      }
      
      return !showError.value;
    };

    const width = computed(() => props.passWidth || 100)

    onMounted(() => {
      dataCheck.addDataCheck(check);
    });

    return { 
      showError,
      check, 
      valueInput, 
      width,
      
      handleInput,
      defaultOptions,
      mockOPtions,
      oneValue,
      twoValue,
      defaultTwoOptions,
      isFriend,
      threeValue,
      defaultThreeOptions,
      setName,
      personName,

      openConfigSource,
      closeDialog,
      handleOpen,
      dialogBtnData,
      handleItemOne,
      handleItemTwo,
      handleItemThree,
      handleItemEdit,
      handleItemSave,
      handleItemCancel,
      handleItemDel,

      isShow,
      addSourceName,
      handleAddItem,
      handleItemAddSave,
      handleItemAddCancel,
      echoSpecialVal,
    };
  },

  methods: {
    out(event: MouseEvent) {
      if(!this.valueInput.must) {
					this.showError = false;
				} else {
					this.check()
				}
    },
  },
});
</script>

<style scoped lang="scss">
@import '@style/extend';
.outer-input {
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
  width: 33.333%;
  padding-right: 10px;
  box-sizing: border-box;
  .input-title {
    padding-bottom: 10px;
    color: $regularText;
    .need {
      color: red;
    }
    .label-name {
      font-size: $fontSize-1
    }
  
  }

  .input-contextPackage {
    display: flex;
    align-items: center;
    .operation-icon {
      width: 30px;
      line-height: 30px;
      height: 30px;
      border: 1px solid #dcdfe6;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 5px;
      border-radius: 4px;
      cursor: pointer;
    }
    .errorhint {
      @extend .error;
      height: 10px;
      display: block;
      line-height: 1;
    }
  }
}

.select-3 {
  padding-right: 5px;
}

.search-border-radius {
  border-radius: 0;
}

.config-source {
  display: flex;
  box-shadow: 0px 2px 10px #dedede;
  border-radius: 8px;
  .source {
    height: 300px;

    .title {
      height: 40px;
      line-height: 40px;
      background-color: #e9e9e9;
      text-align: center;
    }

    .display-area {
      height: calc(100% - 40px);
      overflow-y: auto;
      .area-title {
        height: 35px;
        line-height: 35px;
        width: 100%;
        display: flex;
        justify-content: space-around;
      }

      & > ul, li {
        list-style: none;
        padding: 0;
        margin: 0;
      }

      .item {
        height: 35px;
        line-height: 35px;
        padding-left: 8px;
        cursor: pointer;
        display: flex;
        justify-content: space-around;
      }

      .area-operation {
        & > span {
          padding: 0 10px;
        }
      }

      .item:hover {
        background-color: $a2-Color;

      }

      .not-eidt-item {
        width: 100%;
        text-align: center;
      }

      .add-item {
        height: 35px;
        line-height: 35px;
        border: 1px solid $mainColor;
        border-radius: 8px;
        color: $mainColor;
        user-select: none;
        cursor: pointer;
      }

      .add-item-opration {
        display: flex;
        align-items: center;

        .area-operation {
          & > span {
            padding: 5px 10px;
            background-color: $mainColor;
            margin: 0 10px;

            color: #fff;
            font-weight: bold;
          }
        }
      }
    }
  }
  .source-one {
    flex: 1;
  }
  .source-two {
    flex: 1;
  }
  .source-three {
    flex: 2;
  }
}

.area-active {
  background-color: $mainColor !important;
  color: #fff;
}
</style>
